<template>
  <div class="box-bg-color">
    <div class="filter-container">
      <div class="filter-item">
        <el-input v-model="searchReq.name" placeholder="请输入硬件名称" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.customerName" placeholder="请输入客户名称" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.supplierName" placeholder="请输入供应商名称" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.technologyChargePerson" placeholder="请输入技术负责人" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.purchaseChargePerson" placeholder="请输入采购负责人" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.examinePerson" placeholder="请输入审核负责人" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.phone" placeholder="请输入客户手机号" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-select v-model="searchReq.type" clearable style="width: 180px" placeholder="请选择订单类型">
          <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label" :value="item.value">
            <k-badge :type="item.type" :content="item.label"></k-badge>
          </el-option>
        </el-select>
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="searchDate"
          type="datetime"
          placeholder="选择下单时间"
          @change="dateEvent"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="searchEvent">搜索</el-button>
      </div>
      <div class="filter-action-wrapper upload-wrap">
        <div class="filter-item">
          <el-button type="primary" v-perm="'equipment:index:add'" @click="clickAddEvent">新增硬件录入</el-button>
        </div>
      </div>
    </div>

    <k-table
      ref="tableRef"
      v-bind="tableData"
      :callback="getEquipmentListApi"
      :loading="loading"
      stripe
      current-row-key="id"
    >
      <template #type="{ row }">
        <k-badge
          :type="row.typeInfo.type"
          :content="row.typeInfo.label"
        ></k-badge>
      </template>
      <template #status="{ row }">
        <k-badge
          :type="row.statusInfo.type"
          :content="row.statusInfo.label"
        ></k-badge>
      </template>
      <template #courierCompanyName="{ row }">
        <span class="link-type" v-if="row.courierCompany !== '' && row.courierNumber !== ''" @click="clickExpressEvent(row)">{{ row.courierCompanyName }}</span>
        <span v-else>{{ row.courierCompanyName }}</span>
      </template>
      <template #actions="{ row }">
        <el-button type="primary" plain size="small" @click="clickEditEvent(row.id)" v-perm="'equipment:index:edit'"
          >编辑</el-button
        >
        <el-button type="info" plain size="small" @click="clickDeleteEvent(row)" v-perm="'equipment:index:delete'"
        >删除</el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="clickAuditEvent(row.id)"
          v-if="row.status === 2"
          v-perm="'equipment:index:updateStatus'"
        >审核</el-button>
      </template>
    </k-table>

    <!-- 硬件录入编辑 -->
    <Edit v-model="showEdit" :curr-id="currId" @change="updatePartnerSuccess"></Edit>

    <!-- 硬件录入添加 -->
    <Add v-model="showAdd" @change="createPartnerSuccess"></Add>

    <!-- 硬件录入审核 -->
    <Audit v-model="showAudit" :curr-id="currId" @change="createPartnerSuccess"></Audit>

    <!-- 硬件物流快递信息 -->
    <Express v-model="showExpress" :courierCompanyName="courierCompanyName" :courierNumber="courierNumber" :curr-id="currId"></Express>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, type UploadRawFile } from 'element-plus'
import type { IKTableProps } from 'k-ui'
import { confirmElBox, dateStrFormat, downLoad } from '@/utils'

import {
  getEquipmentList,
  deleteEquipment,
  type QueryEquipmentList,
  type EquipmentApiResult
} from '@/api/equipment'

import type { ListResultData, Pagination } from '@/api/base'
import Edit from './components/Edit.vue'
import Add from './components/add.vue'
import Audit from './components/audit.vue'
import Express from './components/express.vue'
import { hasPerms } from '@/utils/perm'
import { useApiLock } from '_hooks'
import { getExpressList } from '@/utils/express'

const tableRef = ref()
const tableData = ref<IKTableProps<EquipmentApiResult>>({
  mode: 'config',
  data: { list: [], total: 0 },
  auto: true,
  isPager: true,
  pageSize: 20,
  index: true,
  columns: [
    { label: '硬件名称', prop: 'name', default: '--', width: 400, showOverflowTooltip: true },
    { label: '数量', prop: 'number', default: '--', width: 100, sortable: true },
    { label: '客户名称', prop: 'customerName', default: '--', minWidth: 200 },
    { label: '供应商名称', prop: 'supplierName', default: '--', minWidth: 200 },
    { label: '技术负责人', prop: 'technologyChargePerson', default: '--', minWidth: 100 },
    { label: '审核负责人', prop: 'examinePerson', default: '--', minWidth: 100 },
    { label: '快递公司', prop: 'courierCompanyName', default: '未填写', minWidth: 160, slot: true },
    { label: '订单类型', prop: 'type', slot: true },
    { label: '订单状态', prop: 'status', minWidth: 140, slot: true },
    {
      label: '下单日期',
      prop: 'orderDate',
      formatter: (row: EquipmentApiResult) => dateStrFormat(row.orderDate as string),
      width: 100
    },
    {
      label: '创建时间',
      prop: 'createDate',
      formatter: (row: EquipmentApiResult) => dateStrFormat(row.createDate as string),
      width: 100
    }
  ]
})

/* 这里判断是否有整个操作列的权限；如果没有则不显示整列 */
const hasActionPerm = hasPerms(['equipment:index:edit', 'equipment:index:delete', 'equipment:index:updateStatus'])
hasActionPerm && tableData.value.columns.push({ label: '操作', prop: 'actions', fixed: 'right', slot: true, width: 240 })

const orderTypeList = ref<Array<any>>([{
  label: '退货',
  value: 'return',
  type: 'danger'
},
{
  label: '换货',
  value: 'barter',
  type: 'warning'
},
{
  label: '发货',
  value: 'deliver',
  type: 'primary'
}])

const statusList = ref<Array<any>>([{
  label: '审核中',
  value: 2,
  type: 'danger'
},
{
  label: '审核不通过',
  value: 0,
  type: 'warning'
},
{
  label: '审核通过',
  value: 1,
  type: 'primary'
}])

const loading = ref<boolean>(false)

const searchReq = ref<QueryEquipmentList>({
  page: 1,
  size: 20,
  name: '',
  customerName: '',
  supplierName: '',
  technologyChargePerson: '',
  purchaseChargePerson: '',
  examinePerson: '',
  phone: '',
  type: '',
  orderDate: '',
})
// 查询表格事件
const queryReq = ref<QueryEquipmentList>({ page: 1, size: 20 })

const getEquipmentListApi = async ({ page, size }: Pagination) => {
  loading.value = true
  const res = await useApiLock(() => getEquipmentList({ ...queryReq.value, page, size } as QueryEquipmentList), 500)
  loading.value = false
  if (res?.code === 200) {
    const data = res.data as ListResultData<EquipmentApiResult>
    data.list.forEach((item: any) => {
      item.typeInfo = orderTypeList.value.find((oItem: any) => oItem.value === item.type)
      item.statusInfo = statusList.value.find((oItem: any) => oItem.value === item.status)
    })
    tableData.value.data = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

const updatePartnerSuccess = (newPage = {}) => {
  // 在当前页 重新加载数据
  tableRef.value.refreshData(newPage)
}

const createPartnerSuccess = (newPage = {}) => {
  // 在当前页 重新加载数据
  tableRef.value.refreshData(newPage)
}

const searchEvent = () => {
  queryReq.value = Object.assign({}, searchReq.value)
  updatePartnerSuccess({ page: 1, size: 10 })
}

// 硬件录入编辑
const showEdit = ref<boolean>(false)
const currId = ref<string | undefined>(undefined)
const clickEditEvent = (id: string) => {
  currId.value = id
  showEdit.value = true
}

// 硬件录入添加
const showAdd = ref<boolean>(false)
const clickAddEvent = () => {
  showAdd.value = true
}

// 审核
const showAudit = ref<boolean>(false)
const clickAuditEvent = (id: string) => {
  currId.value = id
  showAudit.value = true
}

// 查看物流信息
const showExpress = ref<boolean>(false)
const courierNumber = ref<string>()
const courierCompanyName = ref<string>()
const clickExpressEvent = (row: EquipmentApiResult) => {
  currId.value = row.id
  courierNumber.value = row.courierNumber
  courierCompanyName.value =row.courierCompanyName
  showExpress.value = true
}

const clickDeleteEvent = async (row: EquipmentApiResult) => {
  confirmElBox(`是否确认将硬件录入【${row.name}】删除吗？`, async () => {
    loading.value = true
    const res = await deleteEquipment({ id: row.id, isDelete: 0 })
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: `删除成功` })
      updatePartnerSuccess()
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
    }
  })
}

const searchDate = ref('')

const dateEvent = async (e: any) => {
  if (e) {
    searchReq.value.orderDate = e
  } else {
    searchReq.value.orderDate = undefined;
  }
}

</script>

<style lang="scss" scoped>
.user-account-wrap {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.upload-wrap {
  display: flex;
}
</style>
